package com.yinhe.util.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import com.yinhe.util.RedisUtils;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 前后端交互的类实现消息的接收推送(自己发送给另一个人)
 *
 * @ServerEndpoint(value = "/test/oneToOne") 前端通过此URI 和后端交互，建立连接
 */
@Slf4j
@ServerEndpoint(value = "/test/oneToOne")
@Component
public class OneToOneWebSocket {
    public static OneToOneWebSocket oneToOneWebSocket;
    @Autowired
    private RedisUtils redisUtils;


    @PostConstruct
    public void init() {
        oneToOneWebSocket = this;
        oneToOneWebSocket.redisUtils = this.redisUtils;
    }
    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /** 存放所有在线的客户端 */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
        String param = session.getQueryString();
        if(!StringUtils.isEmpty(param) && param.indexOf("=")>-1){
            String address = param.substring(3);
            log.info("有新连接加入：{}",address);
            updateLineStatus(address,"online");
            sendMessageToManyClient("有新连接加入："+address);
        }
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        String param = session.getQueryString();
        if(!StringUtils.isEmpty(param) && param.indexOf("=")>-1){
            String address = param.substring(3);
            updateLineStatus(address,"offline");
            sendMessageToManyClient("有连接断开："+address);
        }
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message);
        try {
//            MyMessage myMessage = JSON.parseObject(message, MyMessage.class);
//            if (myMessage != null) {
//                Session toSession = clients.get(myMessage.getUserId());
//                if (toSession != null) {
//                    this.sendMessage(myMessage.getMessage(), toSession);
//                }
//            }
        } catch (Exception e) {
            log.error("解析失败：{}", e);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息[{}]", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }

    /**
     * 服务端发送消息给多客户端
     */
    private void sendMessageToManyClient(String message) {
        try {
            log.info("服务端给客户端[{}]发送消息[{}]",  message);
            for (Map.Entry<String, Session> entry : clients.entrySet()) {
                Session session = entry.getValue();
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }

    /**
     * 服务端发送消息给多客户端
     */
    private void updateLineStatus(String id,String status) {
        try {
            JSONObject object = new JSONObject();
            object.put("address",id);
            object.put("status",status);
            oneToOneWebSocket.redisUtils.add("addressInfo",id);
            oneToOneWebSocket.redisUtils.set(id,object);
            Set<Object> ids  = oneToOneWebSocket.redisUtils.setMembers("addressInfo");
            List<Object> list =  oneToOneWebSocket.redisUtils.mget(ids);
            log.info("hello");
//            oneToOneWebSocket.redisUtils.hmGet();
            //查询缓存中是否存在
//            boolean hasKey = redisUtils.exists(id);
//            if(!hasKey){
//                //放入缓存
//                redisUtils.set(id,status);
//            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }
}